<!DOCTYPE html>




<html class="theme-next gemini" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
    
  
  <link href="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.css" rel="stylesheet" type="text/css">




  
  
  
  

  
    
    
  

  
    
      
    

    
  

  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Monda:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|Lobster Two:300,300italic,400,400italic,700,700italic|Source Code Pro:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






  

<link href="https://cdn.staticfile.org/font-awesome/4.6.2/css/font-awesome.css" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=6.0.0" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="http://tva3.sinaimg.cn/crop.206.47.515.515.180/709d5819jw8f4k1tlmnsij20pr0gytdx.jpg?v=6.0.0">


  <link rel="icon" type="image/png" sizes="32x32" href="http://tva3.sinaimg.cn/crop.206.47.515.515.180/709d5819jw8f4k1tlmnsij20pr0gytdx.jpg?v=6.0.0">


  <link rel="icon" type="image/png" sizes="16x16" href="http://tva3.sinaimg.cn/crop.206.47.515.515.180/709d5819jw8f4k1tlmnsij20pr0gytdx.jpg?v=6.0.0">


  <link rel="mask-icon" href="http://tva3.sinaimg.cn/crop.206.47.515.515.180/709d5819jw8f4k1tlmnsij20pr0gytdx.jpg?v=6.0.0" color="#222">





  <meta name="keywords" content="vps, java, python, golang, springmvc">




  


  <link rel="alternate" href="/atom.xml" title="张恒的网络日志" type="application/atom+xml">






<meta name="keywords" content="java, python, go, 技术, 学习笔记, spring">
<meta property="og:type" content="website">
<meta property="og:title" content="张恒的网络日志">
<meta property="og:url" content="http://blog.gavinzh.com/404.html">
<meta property="og:site_name" content="张恒的网络日志">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2020-01-05T08:52:36.912Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="张恒的网络日志">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '6.0.0',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":true,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    fastclick: true,
    lazyload: true,
    tabs: true,
    motion: {"enable":false,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://blog.gavinzh.com/404.html">





  <title>Spring扩展点总结 | 张恒的网络日志</title>
  




<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
            (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
          m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
  ga('create', 'UA-98061925-1', 'auto');
  ga('send', 'pageview');
</script>





</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"> <div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">张恒的网络日志</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description">Zhang Heng's WebSite Blog</h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://blog.gavinzh.com/2017/11/20/spring-develop-summary/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Gavin Zhang">
      <meta itemprop="description" content>
      <meta itemprop="image" content="https://avatars3.githubusercontent.com/u/5567916">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="张恒的网络日志">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">Spring扩展点总结</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-11-20T11:29:00+00:00">2017-11-20</time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/笔记/" itemprop="url" rel="index">
                    <span itemprop="name">笔记</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2017/11/20/spring-develop-summary/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count" data-disqus-identifier="2017/11/20/spring-develop-summary/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          
             <span id="/2017/11/20/spring-develop-summary/" class="leancloud_visitors" data-flag-title="Spring扩展点总结">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>spring中bean的扩展点</p>
<p>经历了一系列复杂的spring应用后，你的项目可能已经用上注解，也用上了xxx.properties，你对这神奇的用法感到欣喜，但你不知道他是怎么被实现的，现在就让我们来揭开这些神秘的面纱。</p>
<a id="more"></a>

<h2 id="BeanDefinition与BeanFactory扩展"><a href="#BeanDefinition与BeanFactory扩展" class="headerlink" title="BeanDefinition与BeanFactory扩展"></a>BeanDefinition与BeanFactory扩展</h2><p>在<a href="/2017/11/17/Spring-create-bean/">Spring生成bean的过程</a>这篇文章中，我们了解了spring在生成bean前会先生成bean的定义，然后注册到BeanFactory中，再之后才能生成bean。那么对于从xml配置好的BeanDefinition，如果想要增加删除修改该怎么办呢？</p>
<h3 id="BeanDefinitionRegistryPostProcessor接口"><a href="#BeanDefinitionRegistryPostProcessor接口" class="headerlink" title="BeanDefinitionRegistryPostProcessor接口"></a>BeanDefinitionRegistryPostProcessor接口</h3><p><code>BeanDefinitionRegistryPostProcessor接口</code>继承了<code>BeanFactoryPostProcessor接口</code>，BeanFactoryPostProcessor接口随后我们也会讲到这个接口。</p>
<h4 id="接口描述"><a href="#接口描述" class="headerlink" title="接口描述"></a>接口描述</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Extension to the standard &#123;<span class="doctag">@link</span> BeanFactoryPostProcessor&#125; SPI, allowing for</span></span><br><span class="line"><span class="comment"> * the registration of further bean definitions &lt;i&gt;before&lt;/i&gt; regular</span></span><br><span class="line"><span class="comment"> * BeanFactoryPostProcessor detection kicks in. In particular,</span></span><br><span class="line"><span class="comment"> * BeanDefinitionRegistryPostProcessor may register further bean definitions</span></span><br><span class="line"><span class="comment"> * which in turn define BeanFactoryPostProcessor instances.</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> Juergen Hoeller</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@since</span> 3.0.1</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> org.springframework.context.annotation.ConfigurationClassPostProcessor</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">BeanDefinitionRegistryPostProcessor</span> <span class="keyword">extends</span> <span class="title">BeanFactoryPostProcessor</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * Modify the application context's internal bean definition registry after its</span></span><br><span class="line"><span class="comment">     * standard initialization. All regular bean definitions will have been loaded,</span></span><br><span class="line"><span class="comment">     * but no beans will have been instantiated yet. This allows for adding further</span></span><br><span class="line"><span class="comment">     * bean definitions before the next post-processing phase kicks in.</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> registry the bean definition registry used by the application context</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@throws</span> org.springframework.beans.BeansException in case of errors</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">postProcessBeanDefinitionRegistry</span><span class="params">(BeanDefinitionRegistry registry)</span> <span class="keyword">throws</span> BeansException</span>;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这个接口扩展了标准的BeanFactoryPostProcessor 接口，允许在普通的BeanFactoryPostProcessor接口实现类执行之前注册更多的BeanDefinition。特别地是，BeanDefinitionRegistryPostProcessor可以注册BeanFactoryPostProcessor的BeanDefinition。</p>
<p>postProcessBeanDefinitionRegistry方法可以修改在<code>BeanDefinitionRegistry接口实现类</code>中注册的任意BeanDefinition，也可以增加和删除BeanDefinition。原因是这个方法执行前所有常规的BeanDefinition已经被加载到<code>BeanDefinitionRegistry接口实现类</code>中，但还没有bean被实例化。</p>
<h4 id="接口应用"><a href="#接口应用" class="headerlink" title="接口应用"></a>接口应用</h4><p>我们仅仅需要写一个类实现接口，然后将这个类配置到spring的xml配置中。以下是我写的一个简单的实现类:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> org.slf4j.Logger;</span><br><span class="line"><span class="keyword">import</span> org.slf4j.LoggerFactory;</span><br><span class="line"><span class="keyword">import</span> org.springframework.beans.BeansException;</span><br><span class="line"><span class="keyword">import</span> org.springframework.beans.factory.config.ConfigurableListableBeanFactory;</span><br><span class="line"><span class="keyword">import</span> org.springframework.beans.factory.support.BeanDefinitionRegistry;</span><br><span class="line"><span class="keyword">import</span> org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DefaultBeanDefinitionRegistryPostProcessor</span> <span class="keyword">implements</span> <span class="title">BeanDefinitionRegistryPostProcessor</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> Logger logger = LoggerFactory.getLogger(<span class="keyword">this</span>.getClass());</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">postProcessBeanDefinitionRegistry</span><span class="params">(BeanDefinitionRegistry registry)</span> <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line">        logger.info(<span class="string">"BeanDefinitionRegistryPostProcessor的postProcessBeanDefinitionRegistry方法,在这里可以增加修改删除bean的定义"</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">postProcessBeanFactory</span><span class="params">(ConfigurableListableBeanFactory beanFactory)</span> <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line">        logger.info(<span class="string">"BeanDefinitionRegistryPostProcessor的postProcessBeanFactory方法,在这里可以对beanFactory做一些操作"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>实际上，Mybatis中<code>org.mybatis.spring.mapper.MapperScannerConfigurer</code>就实现了该方法，在只有接口没有实现类的情况下找到接口方法与sql之间的联系从而生成BeanDefinition并注册。而Spring的<code>org.springframework.context.annotation.ConfigurationClassPostProcessor</code>也是用来将注解@Configuration中的相关生成bean的方法所对应的BeanDefinition进行注册。</p>
<h3 id="BeanFactoryPostProcessor接口"><a href="#BeanFactoryPostProcessor接口" class="headerlink" title="BeanFactoryPostProcessor接口"></a>BeanFactoryPostProcessor接口</h3><p>BeanFactory生成后，如果想对BeanFactory进行一些处理，该怎么办呢？<code>BeanFactoryPostProcessor接口</code>就是用来处理BeanFactory的。</p>
<h4 id="接口描述-1"><a href="#接口描述-1" class="headerlink" title="接口描述"></a>接口描述</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Allows for custom modification of an application context's bean definitions,</span></span><br><span class="line"><span class="comment"> * adapting the bean property values of the context's underlying bean factory.</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;Application contexts can auto-detect BeanFactoryPostProcessor beans in</span></span><br><span class="line"><span class="comment"> * their bean definitions and apply them before any other beans get created.</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;Useful for custom config files targeted at system administrators that</span></span><br><span class="line"><span class="comment"> * override bean properties configured in the application context.</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;See PropertyResourceConfigurer and its concrete implementations</span></span><br><span class="line"><span class="comment"> * for out-of-the-box solutions that address such configuration needs.</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;A BeanFactoryPostProcessor may interact with and modify bean</span></span><br><span class="line"><span class="comment"> * definitions, but never bean instances. Doing so may cause premature bean</span></span><br><span class="line"><span class="comment"> * instantiation, violating the container and causing unintended side-effects.</span></span><br><span class="line"><span class="comment"> * If bean instance interaction is required, consider implementing</span></span><br><span class="line"><span class="comment"> * &#123;<span class="doctag">@link</span> BeanPostProcessor&#125; instead.</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> Juergen Hoeller</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@since</span> 06.07.2003</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> BeanPostProcessor</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> PropertyResourceConfigurer</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">BeanFactoryPostProcessor</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * Modify the application context's internal bean factory after its standard</span></span><br><span class="line"><span class="comment">     * initialization. All bean definitions will have been loaded, but no beans</span></span><br><span class="line"><span class="comment">     * will have been instantiated yet. This allows for overriding or adding</span></span><br><span class="line"><span class="comment">     * properties even to eager-initializing beans.</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> beanFactory the bean factory used by the application context</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@throws</span> org.springframework.beans.BeansException in case of errors</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">postProcessBeanFactory</span><span class="params">(ConfigurableListableBeanFactory beanFactory)</span> <span class="keyword">throws</span> BeansException</span>;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这个接口允许自定义修改应用程序上下文的BeanDefinition，调整上下文的BeanFactory的bean属性值。应用程序上下文可以在BeanFactory的BeanDefinition中自动检测BeanFactoryPostProcessor bean，并在创建任何其他bean之前应用它们。对于定位于系统管理员的自定义配置文件非常有用，它们将覆盖应用程序上下文中配置的bean属性。请参阅PropertyResourceConfigurer及其具体实现，了解解决此类配置需求的开箱即用解决方案。BeanFactoryPostProcessor可能与bean定义交互并修改，但永远不应该将bean实例化。 这样做可能会导致过早的bean实例化，违反容器执行顺序并导致意想不到的副作用。如果需要bean实例交互，请考虑实现BeanPostProcessor接口。</p>
<p>postProcessBeanFactory方法在BeanFactory初始化后，所有的bean定义都被加载，但是没有bean会被实例化时，允许重写或添加属性。</p>
<h4 id="接口应用-1"><a href="#接口应用-1" class="headerlink" title="接口应用"></a>接口应用</h4><p>与DefaultBeanDefinitionRegistryPostProcessor接口一样，实现并配置到spring的xml配置中即可。</p>
<p>最常用的一个应用就是<code>org.springframework.beans.factory.config.PropertyPlaceholderConfigurer</code>，BeanDefinition生成后，可能某些参数是${key}，这个实现类就是把前边这种参数转换成xxx.properties中key所对应的值。</p>
<h2 id="Bean实例化中的扩展"><a href="#Bean实例化中的扩展" class="headerlink" title="Bean实例化中的扩展"></a>Bean实例化中的扩展</h2><p>前一小节关注的是BeanDefinition和BeanFactory，那么在bean的实例化过程中会调用一些特定的接口实现类，这些接口都有哪些？</p>
<h3 id="InstantiationAwareBeanPostProcessor接口"><a href="#InstantiationAwareBeanPostProcessor接口" class="headerlink" title="InstantiationAwareBeanPostProcessor接口"></a>InstantiationAwareBeanPostProcessor接口</h3><h4 id="接口描述-2"><a href="#接口描述-2" class="headerlink" title="接口描述"></a>接口描述</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Subinterface of &#123;<span class="doctag">@link</span> BeanPostProcessor&#125; that adds a before-instantiation callback,</span></span><br><span class="line"><span class="comment"> * and a callback after instantiation but before explicit properties are set or</span></span><br><span class="line"><span class="comment"> * autowiring occurs.</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;Typically used to suppress default instantiation for specific target beans,</span></span><br><span class="line"><span class="comment"> * for example to create proxies with special TargetSources (pooling targets,</span></span><br><span class="line"><span class="comment"> * lazily initializing targets, etc), or to implement additional injection strategies</span></span><br><span class="line"><span class="comment"> * such as field injection.</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;&lt;b&gt;<span class="doctag">NOTE:</span>&lt;/b&gt; This interface is a special purpose interface, mainly for</span></span><br><span class="line"><span class="comment"> * internal use within the framework. It is recommended to implement the plain</span></span><br><span class="line"><span class="comment"> * &#123;<span class="doctag">@link</span> BeanPostProcessor&#125; interface as far as possible, or to derive from</span></span><br><span class="line"><span class="comment"> * &#123;<span class="doctag">@link</span> InstantiationAwareBeanPostProcessorAdapter&#125; in order to be shielded</span></span><br><span class="line"><span class="comment"> * from extensions to this interface.</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> Juergen Hoeller</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> Rod Johnson</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@since</span> 1.2</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#setCustomTargetSourceCreators</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> org.springframework.aop.framework.autoproxy.target.LazyInitTargetSourceCreator</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">InstantiationAwareBeanPostProcessor</span> <span class="keyword">extends</span> <span class="title">BeanPostProcessor</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * Apply this BeanPostProcessor &lt;i&gt;before the target bean gets instantiated&lt;/i&gt;.</span></span><br><span class="line"><span class="comment">     * The returned bean object may be a proxy to use instead of the target bean,</span></span><br><span class="line"><span class="comment">     * effectively suppressing default instantiation of the target bean.</span></span><br><span class="line"><span class="comment">     * &lt;p&gt;If a non-null object is returned by this method, the bean creation process</span></span><br><span class="line"><span class="comment">     * will be short-circuited. The only further processing applied is the</span></span><br><span class="line"><span class="comment">     * &#123;<span class="doctag">@link</span> #postProcessAfterInitialization&#125; callback from the configured</span></span><br><span class="line"><span class="comment">     * &#123;<span class="doctag">@link</span> BeanPostProcessor BeanPostProcessors&#125;.</span></span><br><span class="line"><span class="comment">     * &lt;p&gt;This callback will only be applied to bean definitions with a bean class.</span></span><br><span class="line"><span class="comment">     * In particular, it will not be applied to beans with a "factory-method".</span></span><br><span class="line"><span class="comment">     * &lt;p&gt;Post-processors may implement the extended</span></span><br><span class="line"><span class="comment">     * &#123;<span class="doctag">@link</span> SmartInstantiationAwareBeanPostProcessor&#125; interface in order</span></span><br><span class="line"><span class="comment">     * to predict the type of the bean object that they are going to return here.</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> beanClass the class of the bean to be instantiated</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> beanName the name of the bean</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> the bean object to expose instead of a default instance of the target bean,</span></span><br><span class="line"><span class="comment">     * or &#123;<span class="doctag">@code</span> null&#125; to proceed with default instantiation</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@throws</span> org.springframework.beans.BeansException in case of errors</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@see</span> org.springframework.beans.factory.support.AbstractBeanDefinition#hasBeanClass</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@see</span> org.springframework.beans.factory.support.AbstractBeanDefinition#getFactoryMethodName</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function">Object <span class="title">postProcessBeforeInstantiation</span><span class="params">(Class&lt;?&gt; beanClass, String beanName)</span> <span class="keyword">throws</span> BeansException</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * Perform operations after the bean has been instantiated, via a constructor or factory method,</span></span><br><span class="line"><span class="comment">     * but before Spring property population (from explicit properties or autowiring) occurs.</span></span><br><span class="line"><span class="comment">     * &lt;p&gt;This is the ideal callback for performing field injection on the given bean instance.</span></span><br><span class="line"><span class="comment">     * See Spring's own &#123;<span class="doctag">@link</span> org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor&#125;</span></span><br><span class="line"><span class="comment">     * for a typical example.</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> bean the bean instance created, with properties not having been set yet</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> beanName the name of the bean</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> &#123;<span class="doctag">@code</span> true&#125; if properties should be set on the bean; &#123;<span class="doctag">@code</span> false&#125;</span></span><br><span class="line"><span class="comment">     * if property population should be skipped. Normal implementations should return &#123;<span class="doctag">@code</span> true&#125;.</span></span><br><span class="line"><span class="comment">     * Returning &#123;<span class="doctag">@code</span> false&#125; will also prevent any subsequent InstantiationAwareBeanPostProcessor</span></span><br><span class="line"><span class="comment">     * instances being invoked on this bean instance.</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@throws</span> org.springframework.beans.BeansException in case of errors</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">boolean</span> <span class="title">postProcessAfterInstantiation</span><span class="params">(Object bean, String beanName)</span> <span class="keyword">throws</span> BeansException</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * Post-process the given property values before the factory applies them</span></span><br><span class="line"><span class="comment">     * to the given bean. Allows for checking whether all dependencies have been</span></span><br><span class="line"><span class="comment">     * satisfied, for example based on a "Required" annotation on bean property setters.</span></span><br><span class="line"><span class="comment">     * &lt;p&gt;Also allows for replacing the property values to apply, typically through</span></span><br><span class="line"><span class="comment">     * creating a new MutablePropertyValues instance based on the original PropertyValues,</span></span><br><span class="line"><span class="comment">     * adding or removing specific values.</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> pvs the property values that the factory is about to apply (never &#123;<span class="doctag">@code</span> null&#125;)</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> pds the relevant property descriptors for the target bean (with ignored</span></span><br><span class="line"><span class="comment">     * dependency types - which the factory handles specifically - already filtered out)</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> bean the bean instance created, but whose properties have not yet been set</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> beanName the name of the bean</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> the actual property values to apply to the given bean</span></span><br><span class="line"><span class="comment">     * (can be the passed-in PropertyValues instance), or &#123;<span class="doctag">@code</span> null&#125;</span></span><br><span class="line"><span class="comment">     * to skip property population</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@throws</span> org.springframework.beans.BeansException in case of errors</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@see</span> org.springframework.beans.MutablePropertyValues</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function">PropertyValues <span class="title">postProcessPropertyValues</span><span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">            PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName)</span></span></span><br><span class="line"><span class="function">            <span class="keyword">throws</span> BeansException</span>;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这个接口是BeanPostProcessor的子接口，用于在实例化之后，但在设置显式属性或自动装配之前，设置实例化之前的回调函数。通常用于抑制特定目标bean的默认实例化，例如，创建具有特殊TargetSources（池化目标，延迟初始化目标等）的代理，或者实现其他注入策略，例如字段注入。注意：这个接口是一个专用接口，主要用于框架内的内部使用。 建议尽可能实现简单的BeanPostProcessor接口，或者从InstantiationAwareBeanPostProcessorAdapter派生，以便屏蔽此接口的扩展。</p>
<p>postProcessBeforeInstantiation方法，在目标bean实例化之前创建bean，如果在这里创建了bean，则不会走默认的实例化过程，通常用来创建代理。注意工厂方法生成的bean不会走这个方法。</p>
<p>postProcessAfterInstantiation方法，在目标bean实例化后，但是没有进行属性填充前执行的方法。</p>
<p>postProcessPropertyValues方法，在将给定属性值设置到到给定的bean后，对其进行后处理。 允许检查所有的依赖关系是否被满足，例如基于bean属性设置器上的“Required”注解。还允许替换要应用的属性值，通常通过创建基于原始PropertyValues的新MutablePropertyValues实例，添加或删除特定值。</p>
<h4 id="接口应用-2"><a href="#接口应用-2" class="headerlink" title="接口应用"></a>接口应用</h4><p>这个接口spring不建议用户直接实现，如果必须在这些扩展点应用自己的回调函数，spring建议继承InstantiationAwareBeanPostProcessorAdapter，重写相应的方法即可。</p>
<p><code>org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator</code>，基于beanName创建代理，就是应用了这个接口，在生成bean前生成代理bean，从而替代默认的实例化。</p>
<h3 id="BeanPostProcessor接口"><a href="#BeanPostProcessor接口" class="headerlink" title="BeanPostProcessor接口"></a>BeanPostProcessor接口</h3><h4 id="接口描述-3"><a href="#接口描述-3" class="headerlink" title="接口描述"></a>接口描述</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Factory hook that allows for custom modification of new bean instances,</span></span><br><span class="line"><span class="comment"> * e.g. checking for marker interfaces or wrapping them with proxies.</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;ApplicationContexts can autodetect BeanPostProcessor beans in their</span></span><br><span class="line"><span class="comment"> * bean definitions and apply them to any beans subsequently created.</span></span><br><span class="line"><span class="comment"> * Plain bean factories allow for programmatic registration of post-processors,</span></span><br><span class="line"><span class="comment"> * applying to all beans created through this factory.</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;Typically, post-processors that populate beans via marker interfaces</span></span><br><span class="line"><span class="comment"> * or the like will implement &#123;<span class="doctag">@link</span> #postProcessBeforeInitialization&#125;,</span></span><br><span class="line"><span class="comment"> * while post-processors that wrap beans with proxies will normally</span></span><br><span class="line"><span class="comment"> * implement &#123;<span class="doctag">@link</span> #postProcessAfterInitialization&#125;.</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> Juergen Hoeller</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@since</span> 10.10.2003</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> InstantiationAwareBeanPostProcessor</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> DestructionAwareBeanPostProcessor</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> ConfigurableBeanFactory#addBeanPostProcessor</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> BeanFactoryPostProcessor</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">BeanPostProcessor</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * Apply this BeanPostProcessor to the given new bean instance &lt;i&gt;before&lt;/i&gt; any bean</span></span><br><span class="line"><span class="comment">     * initialization callbacks (like InitializingBean's &#123;<span class="doctag">@code</span> afterPropertiesSet&#125;</span></span><br><span class="line"><span class="comment">     * or a custom init-method). The bean will already be populated with property values.</span></span><br><span class="line"><span class="comment">     * The returned bean instance may be a wrapper around the original.</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> bean the new bean instance</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> beanName the name of the bean</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> the bean instance to use, either the original or a wrapped one;</span></span><br><span class="line"><span class="comment">     * if &#123;<span class="doctag">@code</span> null&#125;, no subsequent BeanPostProcessors will be invoked</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@throws</span> org.springframework.beans.BeansException in case of errors</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@see</span> org.springframework.beans.factory.InitializingBean#afterPropertiesSet</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function">Object <span class="title">postProcessBeforeInitialization</span><span class="params">(Object bean, String beanName)</span> <span class="keyword">throws</span> BeansException</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * Apply this BeanPostProcessor to the given new bean instance &lt;i&gt;after&lt;/i&gt; any bean</span></span><br><span class="line"><span class="comment">     * initialization callbacks (like InitializingBean's &#123;<span class="doctag">@code</span> afterPropertiesSet&#125;</span></span><br><span class="line"><span class="comment">     * or a custom init-method). The bean will already be populated with property values.</span></span><br><span class="line"><span class="comment">     * The returned bean instance may be a wrapper around the original.</span></span><br><span class="line"><span class="comment">     * &lt;p&gt;In case of a FactoryBean, this callback will be invoked for both the FactoryBean</span></span><br><span class="line"><span class="comment">     * instance and the objects created by the FactoryBean (as of Spring 2.0). The</span></span><br><span class="line"><span class="comment">     * post-processor can decide whether to apply to either the FactoryBean or created</span></span><br><span class="line"><span class="comment">     * objects or both through corresponding &#123;<span class="doctag">@code</span> bean instanceof FactoryBean&#125; checks.</span></span><br><span class="line"><span class="comment">     * &lt;p&gt;This callback will also be invoked after a short-circuiting triggered by a</span></span><br><span class="line"><span class="comment">     * &#123;<span class="doctag">@link</span> InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation&#125; method,</span></span><br><span class="line"><span class="comment">     * in contrast to all other BeanPostProcessor callbacks.</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> bean the new bean instance</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> beanName the name of the bean</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> the bean instance to use, either the original or a wrapped one;</span></span><br><span class="line"><span class="comment">     * if &#123;<span class="doctag">@code</span> null&#125;, no subsequent BeanPostProcessors will be invoked</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@throws</span> org.springframework.beans.BeansException in case of errors</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@see</span> org.springframework.beans.factory.InitializingBean#afterPropertiesSet</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@see</span> org.springframework.beans.factory.FactoryBean</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function">Object <span class="title">postProcessAfterInitialization</span><span class="params">(Object bean, String beanName)</span> <span class="keyword">throws</span> BeansException</span>;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这个接口，允许自定义修改新的bean实例，例如检查标记接口或用代理包装，注意，如果有相互依赖的bean，这里可能无法使用代理。</p>
<p>postProcessBeforeInitialization方法，在任何bean初始化回调（如InitializingBean的afterPropertiesSet或自定义init方法）之前，将此BeanPostProcessor应用于给定的新的bean实例。 这个bean已经被填充了属性值。 返回的bean实例可能是原始的包装器。</p>
<p>postProcessAfterInitialization方法，在Bean初始化回调（如InitializingBean的afterPropertiesSet或自定义init方法）之后，将此BeanPostProcessor应用于给定的新bean实例。 这个bean已经被填充了属性值。 返回的bean实例可能是原始的包装器。这个方法也会在InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation方法生成对象后再次不让他生成对象（具体可以参考<a href="/2017/11/17/Spring-create-bean/">Spring生成bean的过程</a>）。</p>
<h4 id="接口应用-3"><a href="#接口应用-3" class="headerlink" title="接口应用"></a>接口应用</h4><p><code>org.springframework.context.support.ApplicationContextAwareProcessor</code>就是在bean初始化回调之前，注入应用上下文的。</p>
<h2 id="其他扩展点"><a href="#其他扩展点" class="headerlink" title="其他扩展点"></a>其他扩展点</h2><h3 id="InitializingBean接口"><a href="#InitializingBean接口" class="headerlink" title="InitializingBean接口"></a>InitializingBean接口</h3><p>在执行完BeanPostProcessor的postProcessBeforeInitialization方法后，如果这个bean实现了InitializingBean接口，则会去调用afterPropertiesSet方法。</p>
<h3 id="各种Aware"><a href="#各种Aware" class="headerlink" title="各种Aware"></a>各种Aware</h3><p>在在执行完BeanPostProcessor的postProcessBeforeInitialization方法前，如果bean实现了BeanNameAware或BeanClassLoaderAware或BeanFactoryAware，则会调用接口相关的方法，入参就是这个bean关心的值。</p>
<p>ApplicationContextAwareProcessor，作用是在一个bean初始化之前，如果这个bean有Aware接口，实现了EnvironmentAware,EmbeddedValueResolverAware，ResourceLoaderAware，ApplicationEventPublisherAware，MessageSourceAware，ApplicationContextAware相关接口，就通过这些aware的相关接口将上下文设置进去，上述接口除了EmbeddedValueResolverAware接口ClassPathXmlApplicationContext没有实现，其他都实现了，也就是说，调用这些接口的方法入参都是ClassPathXmlApplicationContext就可以了。EmbeddedValueResolverAware的入参是EmbeddedValueResolver，它的构造函数入参是上下文中的beanFactory。</p>
<h3 id="BeanDefinition入口扩展"><a href="#BeanDefinition入口扩展" class="headerlink" title="BeanDefinition入口扩展"></a>BeanDefinition入口扩展</h3><p>在定义bean时，可以指定构造函数，设置属性，还可以设置init-method和destroy-method。构造函数不用说，设置属性是在InstantiationAwareBeanPostProcessor#PostProcessPropertyValues方法后执行的，init-method是在InitializingBean的afterPropertiesSet方法后执行的，而destroy-method是在容器关闭是被调用的。</p>
<h2 id="扩展点在spring中的注入"><a href="#扩展点在spring中的注入" class="headerlink" title="扩展点在spring中的注入"></a>扩展点在spring中的注入</h2><p>前三小节我们了解了很多扩展点，那这些扩展点中的接口是怎么在spring中生效的呢，换句话说在什么时候被调用或被添加到BeanFactory中等待调用呢？</p>
<h3 id="容器级别"><a href="#容器级别" class="headerlink" title="容器级别"></a>容器级别</h3><p>我们得从上下文的抽象类AbstractApplicationContext#refresh方法讲起。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">refresh</span><span class="params">()</span> <span class="keyword">throws</span> BeansException, IllegalStateException </span>&#123;</span><br><span class="line">    <span class="keyword">synchronized</span> (<span class="keyword">this</span>.startupShutdownMonitor) &#123;</span><br><span class="line">        <span class="comment">// Prepare this context for refreshing.</span></span><br><span class="line">		<span class="comment">// 设置上下文启动时间和活跃标记，同时加载属性资源。</span></span><br><span class="line">        prepareRefresh();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// Tell the subclass to refresh the internal bean factory.</span></span><br><span class="line">		<span class="comment">// 停掉之前启动的beanFactory如果有的话，同时新生成一个beanFactory，加载配置中的BeanDefinition。</span></span><br><span class="line">        ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// Prepare the bean factory for use in this context.</span></span><br><span class="line">		<span class="comment">// 给beanFactory设置类加载器，添加后置处理器`ApplicationContextAwareProcessor`等等。</span></span><br><span class="line">        prepareBeanFactory(beanFactory);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">// Allows post-processing of the bean factory in context subclasses.</span></span><br><span class="line">            postProcessBeanFactory(beanFactory);</span><br><span class="line"></span><br><span class="line">            <span class="comment">// Invoke factory processors registered as beans in the context.</span></span><br><span class="line">            invokeBeanFactoryPostProcessors(beanFactory);</span><br><span class="line"></span><br><span class="line">            <span class="comment">// Register bean processors that intercept bean creation.</span></span><br><span class="line">            registerBeanPostProcessors(beanFactory);</span><br><span class="line"></span><br><span class="line">            <span class="comment">// Initialize message source for this context.</span></span><br><span class="line">            initMessageSource();</span><br><span class="line"></span><br><span class="line">            <span class="comment">// Initialize event multicaster for this context.</span></span><br><span class="line">            initApplicationEventMulticaster();</span><br><span class="line"></span><br><span class="line">            <span class="comment">// Initialize other special beans in specific context subclasses.</span></span><br><span class="line">            onRefresh();</span><br><span class="line"></span><br><span class="line">            <span class="comment">// Check for listener beans and register them.</span></span><br><span class="line">            registerListeners();</span><br><span class="line"></span><br><span class="line">            <span class="comment">// Instantiate all remaining (non-lazy-init) singletons.</span></span><br><span class="line">            finishBeanFactoryInitialization(beanFactory);</span><br><span class="line"></span><br><span class="line">            <span class="comment">// Last step: publish corresponding event.</span></span><br><span class="line">            finishRefresh();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">catch</span> (BeansException ex) &#123;</span><br><span class="line">            <span class="keyword">if</span> (logger.isWarnEnabled()) &#123;</span><br><span class="line">                logger.warn(<span class="string">"Exception encountered during context initialization - "</span> +</span><br><span class="line">                        <span class="string">"cancelling refresh attempt: "</span> + ex);</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="comment">// Destroy already created singletons to avoid dangling resources.</span></span><br><span class="line">            destroyBeans();</span><br><span class="line"></span><br><span class="line">            <span class="comment">// Reset 'active' flag.</span></span><br><span class="line">            cancelRefresh(ex);</span><br><span class="line"></span><br><span class="line">            <span class="comment">// Propagate exception to caller.</span></span><br><span class="line">            <span class="keyword">throw</span> ex;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">finally</span> &#123;</span><br><span class="line">            <span class="comment">// Reset common introspection caches in Spring's core, since we</span></span><br><span class="line">            <span class="comment">// might not ever need metadata for singleton beans anymore...</span></span><br><span class="line">            resetCommonCaches();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>invokeBeanFactoryPostProcessors(beanFactory)方法就是第一小节提到的BeanDefinitionRegistryPostProcessor和BeanFactoryPostProcessor的调用。</p>
<p><strong>invokeBeanFactoryPostProcessors方法的调用逻辑：</strong></p>
<blockquote>
<p>如果beanFactory是BeanDefinitionRegistry的实现类</p>
</blockquote>
<blockquote>
<blockquote>
<p>拿到入参所有的BeanFactoryPostProcessor接口实现类，挑选出实现BeanDefinitionRegistryPostProcessor接口的实现类先执行postProcessBeanDefinitionRegistry方法。</p>
</blockquote>
</blockquote>
<blockquote>
<blockquote>
<p>接下来调用beanFactory中实现BeanDefinitionRegistryPostProcessor接口的实现类中实现PriorityOrdered接口的实现类，调用这些实现类前先根据PriorityOrdered的getOrder方法进行排序，然后再按顺序调用postProcessBeanDefinitionRegistry方法。</p>
</blockquote>
</blockquote>
<blockquote>
<blockquote>
<p>接下来再调用beanFactory中实现BeanDefinitionRegistryPostProcessor接口的实现类中实现了Ordered接口的类，也是按顺序调用postProcessBeanDefinitionRegistry方法。</p>
</blockquote>
</blockquote>
<blockquote>
<blockquote>
<p>最后调用beanFactory中其他的实现BeanDefinitionRegistryPostProcessor接口的实现类的postProcessBeanDefinitionRegistry方法。</p>
</blockquote>
</blockquote>
<blockquote>
<blockquote>
<p>最后的最后，先调用入参中所有实现BeanDefinitionRegistryPostProcessor接口的实现类的postProcessBeanFactory方法，再调用入参中实现了BeanFactoryPostProcessor接口的实现类的postProcessBeanFactory方法。</p>
</blockquote>
</blockquote>
<blockquote>
<p>如果不是则只把入参中的BeanFactoryPostProcessor实现类全部调用一遍。</p>
</blockquote>
<blockquote>
<p>上边都做完了，接着从beanFactory中获取实现了BeanFactoryPostProcessor接口的bean（没有被执行过），也是分为三类，PriorityOrdered组优先调用，Ordered其次，其他垫底。<br>最终清除beanFactory的metaData缓存（主要是清除类与beanname的映射缓存）</p>
</blockquote>
<p>registerBeanPostProcessors(beanFactory)方法就是第二小节中BeanPostProcessor接口实现类的注册。</p>
<p><strong>registerBeanPostProcessors方法的调用逻辑：</strong></p>
<blockquote>
<p>先添加BeanPostProcessorChecker。</p>
</blockquote>
<blockquote>
<p>然后把beanFactory中实现BeanPostProcessor接口的实现类分成四个部分分别添加到beanFactory。</p>
</blockquote>
<blockquote>
<p>PriorityOrdered部分，实现了PriorityOrdered接口且并不属于MergedBeanDefinitionPostProcessor的</p>
</blockquote>
<blockquote>
<p>Ordered部分，实现了Ordered接口且并不属于MergedBeanDefinitionPostProcessor的</p>
</blockquote>
<blockquote>
<p>其他的不属于MergedBeanDefinitionPostProcessor的</p>
</blockquote>
<blockquote>
<p>属于MergedBeanDefinitionPostProcessor的</p>
</blockquote>
<blockquote>
<p>其中PriorityOrdered和Ordered部分先排序，然后按上边的顺序分别加入到beanFactory的beanPostProcessors属性中</p>
</blockquote>
<h3 id="bean级别"><a href="#bean级别" class="headerlink" title="bean级别"></a>bean级别</h3><p>其余的bean上的接口属性之类的，都是在bean的生成中逐个调用的。</p>
<h2 id="小节"><a href="#小节" class="headerlink" title="小节"></a>小节</h2><p>下面由一张图来总结一下扩展点之间的调用顺序。</p>
<p><img src="/images/pasted-92.png" alt="upload successful"></p>

      
    </div>
    
    
    

    

    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    Gavin Zhang
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://blog.gavinzh.com/2017/11/20/spring-develop-summary/" title="Spring扩展点总结">http://blog.gavinzh.com/2017/11/20/spring-develop-summary/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/java/" rel="tag"># java</a>
          
            <a href="/tags/spring/" rel="tag"># spring</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/11/17/Spring-create-bean/" rel="next" title="Spring生成bean的过程">
                <i class="fa fa-chevron-left"></i> Spring生成bean的过程
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/11/26/Spring-BeanDefinition-parser/" rel="prev" title="Spring的BeanDefinition解析">
                Spring的BeanDefinition解析 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="disqus_thread">
        <noscript>
          Please enable JavaScript to view the
          <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a>
        </noscript>
      </div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="https://avatars3.githubusercontent.com/u/5567916" alt="Gavin Zhang">
            
              <p class="site-author-name" itemprop="name">Gavin Zhang</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">129</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">7</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">158</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/jiangmitiao" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:me at gavinzh.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#BeanDefinition与BeanFactory扩展"><span class="nav-number">1.</span> <span class="nav-text">BeanDefinition与BeanFactory扩展</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#BeanDefinitionRegistryPostProcessor接口"><span class="nav-number">1.1.</span> <span class="nav-text">BeanDefinitionRegistryPostProcessor接口</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#接口描述"><span class="nav-number">1.1.1.</span> <span class="nav-text">接口描述</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#接口应用"><span class="nav-number">1.1.2.</span> <span class="nav-text">接口应用</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#BeanFactoryPostProcessor接口"><span class="nav-number">1.2.</span> <span class="nav-text">BeanFactoryPostProcessor接口</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#接口描述-1"><span class="nav-number">1.2.1.</span> <span class="nav-text">接口描述</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#接口应用-1"><span class="nav-number">1.2.2.</span> <span class="nav-text">接口应用</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Bean实例化中的扩展"><span class="nav-number">2.</span> <span class="nav-text">Bean实例化中的扩展</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#InstantiationAwareBeanPostProcessor接口"><span class="nav-number">2.1.</span> <span class="nav-text">InstantiationAwareBeanPostProcessor接口</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#接口描述-2"><span class="nav-number">2.1.1.</span> <span class="nav-text">接口描述</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#接口应用-2"><span class="nav-number">2.1.2.</span> <span class="nav-text">接口应用</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#BeanPostProcessor接口"><span class="nav-number">2.2.</span> <span class="nav-text">BeanPostProcessor接口</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#接口描述-3"><span class="nav-number">2.2.1.</span> <span class="nav-text">接口描述</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#接口应用-3"><span class="nav-number">2.2.2.</span> <span class="nav-text">接口应用</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#其他扩展点"><span class="nav-number">3.</span> <span class="nav-text">其他扩展点</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#InitializingBean接口"><span class="nav-number">3.1.</span> <span class="nav-text">InitializingBean接口</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#各种Aware"><span class="nav-number">3.2.</span> <span class="nav-text">各种Aware</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#BeanDefinition入口扩展"><span class="nav-number">3.3.</span> <span class="nav-text">BeanDefinition入口扩展</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#扩展点在spring中的注入"><span class="nav-number">4.</span> <span class="nav-text">扩展点在spring中的注入</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#容器级别"><span class="nav-number">4.1.</span> <span class="nav-text">容器级别</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#bean级别"><span class="nav-number">4.2.</span> <span class="nav-text">bean级别</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#小节"><span class="nav-number">5.</span> <span class="nav-text">小节</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
            <span id="scrollpercent"><span>0</span>%</span>
          
        </div>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2013 &mdash; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Gavin Zhang</span>

  

  
</div>





<div>
	<a href="http://www.beian.miit.gov.cn/" target="_blank">陕ICP备17010002号-1</a>
</div>





        




  <script type="text/javascript">
    (function() {
      var hm = document.createElement("script");
      hm.src = "//tajs.qq.com/stats?sId=61868582";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <div style="display: none;">
    <script src="//s95.cnzz.com/z_stat.php?id=1261805793&web_id=1261805793" language="JavaScript"></script>
  </div>



        
      </div>
    </footer>

    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>





  



  






  













  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js"></script>
  

  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/fastclick/1.0.6/fastclick.js"></script>
  

  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/jquery.lazyload/1.9.1/jquery.lazyload.min.js"></script>
  

  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/velocity/2.0.5/velocity.min.js"></script>
  

  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/velocity/2.0.5/velocity.min.js"></script>
  

  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.0.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.0.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=6.0.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=6.0.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.0.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.0.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.0.0"></script>



  


  

    
      <script id="dsq-count-scr" src="https://zhang-hengs-website-blog.disqus.com/count.js" async></script>
    

    
      <script type="text/javascript">
        var disqus_config = function () {
          this.page.url = 'http://blog.gavinzh.com/2017/11/20/spring-develop-summary/';
          this.page.identifier = '2017/11/20/spring-develop-summary/';
          this.page.title = 'Spring扩展点总结';
        };
        var d = document, s = d.createElement('script');
        s.src = 'https://zhang-hengs-website-blog.disqus.com/embed.js';
        s.setAttribute('data-timestamp', '' + +new Date());
        (d.head || d.body).appendChild(s);
      </script>
    

  




	





  














  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("EhAMmIXTRGtethTcgYwA9afH-gzGzoHsz", "jzP1TaBhMleAUgPLXyB0h8oQ");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  

  
  


  
  <script type="text/javascript" src="/js/src/js.cookie.js?v=6.0.0"></script>
  <script type="text/javascript" src="/js/src/scroll-cookie.js?v=6.0.0"></script>


  

</body>
</html>
